package endpoint

import (
	"mcode/apps/admin/internal/endpoint/validate"
	"mcode/apps/admin/internal/entity"
	"mcode/apps/admin/internal/usecase"
	"mcode/pkg/auth"
	"mcode/pkg/ctx"
	"mcode/pkg/logger"
	"mcode/pkg/query"
	"mcode/pkg/response"
	"mcode/pkg/validator"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type UserHandler struct {
	userUseCase usecase.UserUseCase
	validator   *validator.Validator
}

func NewUserHandler(userUseCase usecase.UserUseCase, validator *validator.Validator) *UserHandler {
	return &UserHandler{
		userUseCase: userUseCase,
		validator:   validator,
	}
}

func (h *UserHandler) GetUser(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的用户ID")
		return
	}

	user, err := h.userUseCase.GetUser(c.Request.Context(), uint(id))
	if err != nil {
		response.Error(c, http.StatusNotFound, "用户不存在")
		return
	}

	response.Success(c, user)
}

func (h *UserHandler) UpdateUser(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的用户ID")
		return
	}

	var req validate.UpdateUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(&req); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}

	user := &entity.User{
		ID:       uint(id),
		Username: req.Username,
		Email:    req.Email,
	}

	if err := h.userUseCase.UpdateUser(c.Request.Context(), user); err != nil {
		response.Error(c, http.StatusInternalServerError, "更新用户失败")
		return
	}

	response.Success(c, user)
}

func (h *UserHandler) DeleteUser(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的用户ID")
		return
	}

	if err := h.userUseCase.DeleteUser(c.Request.Context(), uint(id)); err != nil {
		response.Error(c, http.StatusInternalServerError, "删除用户失败")
		return
	}

	response.Success(c, nil)
}

func (h *UserHandler) Register(c *gin.Context) {
	var req validate.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(&req); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}
	// todo 用户注册逻辑
	user := new(entity.User)
	user.Username = req.Username
	user.Email = req.Email
	user.Password = req.Password
	// 处理注册逻辑
	if err := h.userUseCase.CreateUser(c.Request.Context(), user); err != nil {
		response.Error(c, http.StatusInternalServerError, "注册用户失败")
		return
	}

	response.Created(c, user)
}

func (h *UserHandler) Login(c *gin.Context) {
	var req validate.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(&req); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}

	// TODO: 实现实际的登录逻辑
	jwtMessage, err := auth.GetJWTManager().GenerateTokenPair(1, req.Username, "test")
	if err != nil {
		response.ServerError(c, err)
		return
	}
	response.Success(c, jwtMessage)
}

func (h *UserHandler) RefreshToken(c *gin.Context) {
	var req validate.RefreshTokenRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(&req); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}

	// TODO: token相关逻辑
	jwtMessage, err := auth.GetJWTManager().RefreshToken(req.Token)
	if err != nil {
		response.ServerError(c, err)
		return
	}
	response.Success(c, jwtMessage)
}

func (h *UserHandler) GetProfile(c *gin.Context) {
	// TODO: 实现获取用户资料的逻辑
	response.Success(c, gin.H{
		"user": map[string]interface{}{"id": 1, "name": "用户"},
	})
}

func (h *UserHandler) TestUser(c *gin.Context) {
	// TODO: 实现获取用户资料的逻辑
	logger.GetLogger().Info("测试")
	response.Success(c, gin.H{
		"user": map[string]interface{}{"id": 1, "name": "用户"},
	})
}

// List List取用户列表
func (h *UserHandler) List(c *gin.Context) {
	params := query.NewQuery().
		AddCondition("status", query.OpEq, 1).
		AddOrderBy("id DESC").
		SetPagination(ctx.GetPagination(c)).
		Select("id", "username", "email", "role", "status", "created_at", "updated_at")
	result, err := h.userUseCase.List(c.Request.Context(), params)
	if err != nil {
		response.ServerError(c, err)
		return
	}

	response.Success(c, result)
}
